// 配置列表页面脚本

// 全局变量
let configs = [];
let previewChart = null;
let deleteConfigId = null;

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 加载配置列表
    loadConfigs();
    
    // 初始化预览图表
    previewChart = echarts.init(document.getElementById('previewChart'));
    
    // 绑定搜索按钮事件
    document.getElementById('searchBtn').addEventListener('click', searchConfigs);
    
    // 绑定搜索输入框回车事件
    document.getElementById('searchInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            searchConfigs();
        }
    });
    
    // 绑定删除确认按钮事件
    document.getElementById('confirmDeleteBtn').addEventListener('click', confirmDelete);
    
    // 监听窗口大小变化，调整预览图表大小
    window.addEventListener('resize', function() {
        if (previewChart) {
            previewChart.resize();
        }
    });
    
    // 监听模态框显示事件，调整预览图表大小
    document.getElementById('previewModal').addEventListener('shown.bs.modal', function() {
        if (previewChart) {
            previewChart.resize();
        }
    });
});

// 加载配置列表
function loadConfigs() {
    const token = localStorage.getItem('token');
    
    fetch('/api/configs', {
        headers: {
            'Authorization': `Bearer ${token}`
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            configs = data.data;
            renderConfigsList(configs);
        } else {
            showError('加载配置列表失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('加载配置列表失败:', error);
        showError('加载配置列表失败，请重试');
    });
}

// 渲染配置列表
function renderConfigsList(configsList) {
    const configsListElement = document.getElementById('configsList');
    const noDataMessage = document.getElementById('noDataMessage');
    
    // 清空列表
    configsListElement.innerHTML = '';
    
    // 检查是否有配置
    if (configsList.length === 0) {
        noDataMessage.classList.remove('d-none');
        return;
    }
    
    // 隐藏无数据提示
    noDataMessage.classList.add('d-none');
    
    // 添加配置到列表
    configsList.forEach(config => {
        const row = document.createElement('tr');
        
        // 格式化日期
        const createdAt = new Date(config.createdAt).toLocaleString();
        const updatedAt = new Date(config.updatedAt).toLocaleString();
        
        row.innerHTML = `
            <td>
                <a href="#" class="config-name" data-id="${config._id}">${config.name}</a>
            </td>
            <td>${config.description || '-'}</td>
            <td>${createdAt}</td>
            <td>${updatedAt}</td>
            <td>
                <div class="btn-group btn-group-sm">
                    <button class="btn btn-outline-primary preview-btn" data-id="${config._id}" title="预览">
                        <i class="bi bi-eye"></i>
                    </button>
                    <a href="editor.html?id=${config._id}" class="btn btn-outline-secondary" title="编辑">
                        <i class="bi bi-pencil"></i>
                    </a>
                    <button class="btn btn-outline-danger delete-btn" data-id="${config._id}" data-name="${config.name}" title="删除">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
            </td>
        `;
        
        configsListElement.appendChild(row);
    });
    
    // 绑定配置名称点击事件
    document.querySelectorAll('.config-name').forEach(element => {
        element.addEventListener('click', function(e) {
            e.preventDefault();
            const configId = this.getAttribute('data-id');
            previewConfig(configId);
        });
    });
    
    // 绑定预览按钮点击事件
    document.querySelectorAll('.preview-btn').forEach(button => {
        button.addEventListener('click', function() {
            const configId = this.getAttribute('data-id');
            previewConfig(configId);
        });
    });
    
    // 绑定删除按钮点击事件
    document.querySelectorAll('.delete-btn').forEach(button => {
        button.addEventListener('click', function() {
            const configId = this.getAttribute('data-id');
            const configName = this.getAttribute('data-name');
            showDeleteConfirmation(configId, configName);
        });
    });
}

// 搜索配置
function searchConfigs() {
    const searchTerm = document.getElementById('searchInput').value.trim();
    
    if (!searchTerm) {
        renderConfigsList(configs);
        return;
    }
    
    const token = localStorage.getItem('token');
    
    fetch(`/api/configs/search?query=${encodeURIComponent(searchTerm)}`, {
        headers: {
            'Authorization': `Bearer ${token}`
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            renderConfigsList(data.data);
        } else {
            showError('搜索失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('搜索失败:', error);
        showError('搜索失败，请重试');
    });
}

// 预览配置
function previewConfig(configId) {
    const token = localStorage.getItem('token');
    
    fetch(`/api/configs/${configId}`, {
        headers: {
            'Authorization': `Bearer ${token}`
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 设置模态框标题
            document.getElementById('previewConfigName').textContent = `预览: ${data.data.name}`;
            
            // 设置编辑按钮链接
            document.getElementById('editConfigBtn').href = `editor.html?id=${configId}`;
            
            // 渲染图表
            previewChart.setOption(data.data.config, true);
            
            // 显示模态框
            const previewModal = new bootstrap.Modal(document.getElementById('previewModal'));
            previewModal.show();
        } else {
            showError('加载配置失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('加载配置失败:', error);
        showError('加载配置失败，请重试');
    });
}

// 显示删除确认对话框
function showDeleteConfirmation(configId, configName) {
    deleteConfigId = configId;
    document.getElementById('deleteConfigName').textContent = configName;
    
    const deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));
    deleteModal.show();
}

// 确认删除配置
function confirmDelete() {
    if (!deleteConfigId) return;
    
    const token = localStorage.getItem('token');
    
    fetch(`/api/configs/${deleteConfigId}`, {
        method: 'DELETE',
        headers: {
            'Authorization': `Bearer ${token}`
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 关闭模态框
            const deleteModal = bootstrap.Modal.getInstance(document.getElementById('deleteModal'));
            deleteModal.hide();
            
            // 重新加载配置列表
            loadConfigs();
        } else {
            showError('删除失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('删除失败:', error);
        showError('删除失败，请重试');
    });
}

// 显示错误信息
function showError(message) {
    alert(message);
}